#include<stdio.h>
#include<stdlib.h>
#include <unistd.h>  // 引入usleep函数声明
#include <linux/fb.h>
#include <linux/input.h>//事件结构体头文件
#include <time.h>    // 用于随机数生成
#include "taiji.h"
#include "slide.h"
#include "sheet.h"
#include "local.h"  // 添加local.h头文件，以访问jmpbuffer变量
#include <setjmp.h>

// 计算机AI下子函数
void computerMove(int *num) {
    int best_x = -1, best_y = -1;
    int score[16][16] = {0}; // 评分矩阵
    int max_score = 0;
    
    // 1. 寻找己方(白棋)的进攻点
    for (int i = 0; i < 16; i++) {
        for (int j = 0; j < 16; j++) {
            if (sheet[i][j] == 0) { // 空位
                int current_score = 0;
                
                // 检查横向
                int count = 1;
                for (int k = j + 1; k < 16 && sheet[i][k] == 2; k++) count++;
                for (int k = j - 1; k >= 0 && sheet[i][k] == 2; k--) count++;
                if (count >= 4) current_score += 1000;
                else if (count == 3) current_score += 100;
                else if (count == 2) current_score += 10;
                else if (count == 1) current_score += 1;
                
                // 检查纵向
                count = 1;
                for (int k = i + 1; k < 16 && sheet[k][j] == 2; k++) count++;
                for (int k = i - 1; k >= 0 && sheet[k][j] == 2; k--) count++;
                if (count >= 4) current_score += 1000;
                else if (count == 3) current_score += 100;
                else if (count == 2) current_score += 10;
                else if (count == 1) current_score += 1;
                
                // 检查右下对角线
                count = 1;
                for (int k = i + 1, l = j + 1; k < 16 && l < 16 && sheet[k][l] == 2; k++, l++) count++;
                for (int k = i - 1, l = j - 1; k >= 0 && l >= 0 && sheet[k][l] == 2; k--, l--) count++;
                if (count >= 4) current_score += 1000;
                else if (count == 3) current_score += 100;
                else if (count == 2) current_score += 10;
                else if (count == 1) current_score += 1;
                
                // 检查左下对角线
                count = 1;
                for (int k = i + 1, l = j - 1; k < 16 && l >= 0 && sheet[k][l] == 2; k++, l--) count++;
                for (int k = i - 1, l = j + 1; k >= 0 && l < 16 && sheet[k][l] == 2; k--, l++) count++;
                if (count >= 4) current_score += 1000;
                else if (count == 3) current_score += 100;
                else if (count == 2) current_score += 10;
                else if (count == 1) current_score += 1;
                
                score[i][j] += current_score;
            }
        }
    }
    
    // 2. 寻找防守点(阻止黑棋)
    for (int i = 0; i < 16; i++) {
        for (int j = 0; j < 16; j++) {
            if (sheet[i][j] == 0) { // 空位
                int current_score = 0;
                
                // 检查横向
                int count = 1;
                for (int k = j + 1; k < 16 && sheet[i][k] == 1; k++) count++;
                for (int k = j - 1; k >= 0 && sheet[i][k] == 1; k--) count++;
                if (count >= 4) current_score += 2000; // 防守优先级高于进攻
                else if (count == 3) current_score += 200;
                else if (count == 2) current_score += 20;
                else if (count == 1) current_score += 2;
                
                // 检查纵向
                count = 1;
                for (int k = i + 1; k < 16 && sheet[k][j] == 1; k++) count++;
                for (int k = i - 1; k >= 0 && sheet[k][j] == 1; k--) count++;
                if (count >= 4) current_score += 2000;
                else if (count == 3) current_score += 200;
                else if (count == 2) current_score += 20;
                else if (count == 1) current_score += 2;
                
                // 检查右下对角线
                count = 1;
                for (int k = i + 1, l = j + 1; k < 16 && l < 16 && sheet[k][l] == 1; k++, l++) count++;
                for (int k = i - 1, l = j - 1; k >= 0 && l >= 0 && sheet[k][l] == 1; k--, l--) count++;
                if (count >= 4) current_score += 2000;
                else if (count == 3) current_score += 200;
                else if (count == 2) current_score += 20;
                else if (count == 1) current_score += 2;
                
                // 检查左下对角线
                count = 1;
                for (int k = i + 1, l = j - 1; k < 16 && l >= 0 && sheet[k][l] == 1; k++, l--) count++;
                for (int k = i - 1, l = j + 1; k >= 0 && l < 16 && sheet[k][l] == 1; k--, l++) count++;
                if (count >= 4) current_score += 2000;
                else if (count == 3) current_score += 200;
                else if (count == 2) current_score += 20;
                else if (count == 1) current_score += 2;
                
                score[i][j] += current_score;
                
                // 更新最高分位置
                if (score[i][j] > max_score) {
                    max_score = score[i][j];
                    best_x = i;
                    best_y = j;
                }
            }
        }
    }
    
    // 3. 如果没有找到明显的进攻或防守点，选择一个随机位置
    if (best_x == -1 || best_y == -1) {
        while (1) {
            best_x = rand() % 16;
            best_y = rand() % 16;
            if (sheet[best_x][best_y] == 0) {
                break;
            }
        }
    }
    
    // 4. 在最佳位置下子
    int x = best_x * 30 + 10;
    int y = best_y * 30 + 10;
    
    // 直接在屏幕上绘制棋子，不使用prepare_double_buffer避免清空屏幕
    
    // 绘制白棋棋子
    draw_round1(x, y, 10, 0xF5F5F5);
    draw_round2(x, y, 10, 0xF5F5F5);
    
    // 更新回合指示器为黑棋
    draw_round1(600, 140, 30, 0x000000);
    draw_round2(600, 140, 30, 0x000000);
    
    // 更新棋盘数据
    sheet[best_x][best_y] = 2;
    (*num)++;
}

void local_wzq()
{
    again: 
    //使用双缓冲技术初始化界面，避免闪烁
    prepare_double_buffer();
    
    // 在后缓冲区绘制所有初始化内容
    draw_background_buffer(0xffffff);
    draw_picture_buffer(0, 0, "./picture/checkerboard.bmp");
    draw_picture_buffer(500, 0, "./picture/what.bmp");
    draw_picture_buffer(700, 380, "./picture/huitui.bmp");
    draw_picture_buffer(480, 400, "./picture/gameagain.bmp");
    draw_picture_buffer(720, 0, "./picture/surrender.bmp");
    
    // 特殊处理checkerboard函数，先临时切换到缓冲区绘制
    int *temp_lcd_fp = lcd_fp;
    lcd_fp = back_buffer;
    checkerboard();
    lcd_fp = temp_lcd_fp;

    //黑棋先下 - 在后缓冲区绘制回合提示
    draw_round_buffer(600, 140, 30, 0x000000);
    
    // 一次性交换缓冲区，避免闪烁
    swap_buffer();
    int num=0;//记录下子数
    int sum1=0,sum2=0;//记录连子数
    int gameEnded = 0; // 标记游戏是否结束
    
    // 初始化随机数生成器
    srand(time(NULL));
    
    // 游戏主循环
    while (1)
    {
        // 玩家回合（黑棋）
        if (num % 2 == 0)
        {
            // 等待玩家触摸输入
            int touch_result = direction();
            
            if(touch_result == 0) // 检测到有效点击
            {
                //返回主界面
                if(end_x<800 && end_y>380 &&end_x>700 &&end_y<480)
                {
                    chess_again();
                    longjmp(jmpbuffer,1);
                }
                //重开
                else if(end_x<560 && end_y>380 &&end_x>480 &&end_y<480)
                {
                    // 彻底重置所有游戏状态
                    chess_again(); // 清空棋盘数组
                    num = 0;       // 重置落子数
                    sum1 = 0;      // 重置连子计数
                    sum2 = 0;
                    gameEnded = 0; // 重置结束状态
                    
                    // 使用双缓冲技术重绘界面，避免闪烁
                    prepare_double_buffer();
                    
                    // 在后缓冲区绘制所有内容
                    draw_background_buffer(0xffffff);
                    draw_picture_buffer(0, 0, "./picture/checkerboard.bmp");
                    draw_picture_buffer(500, 0, "./picture/what.bmp");
                    draw_picture_buffer(700, 380, "./picture/huitui.bmp");
                    draw_picture_buffer(480, 400, "./picture/gameagain.bmp");
                    draw_picture_buffer(720, 0, "./picture/surrender.bmp");
                    
                    // 特殊处理checkerboard函数，先临时切换到缓冲区绘制
                    int *temp_lcd_fp = lcd_fp;
                    lcd_fp = back_buffer;
                    checkerboard();
                    lcd_fp = temp_lcd_fp;
                    
                    // 在后缓冲区绘制回合提示
                    draw_round_buffer(600, 140, 30, 0x000000);
                    
                    // 一次性交换缓冲区，避免闪烁
                    swap_buffer();
                    
                    goto again;
                }
                //投降
                else if(end_x<800 && end_y>0 &&end_x>720 &&end_y<80)
                {
                    draw_picture(650,120,"./picture/bai.bmp");
                    gameEnded = 1;
                    break;
                }
                //玩家下子
                else
                {
                    // 检查是否点击在有效棋盘位置
                    int old_num = num;
                    int valid_move = 0;
                    
                    for(int i=10; i<480; i=i+30)
                    {
                        for(int j=10; j<480; j=j+30)
                        {
                            if(abs(end_x-i)<15 && abs(end_y-j)<15)
                            {
                                int x=i/30;
                                int y=j/30;
                                if(sheet[x][y]==0)
                                {
                                    // 直接在屏幕上绘制棋子，不使用prepare_double_buffer避免清空屏幕
                                    
                                    // 绘制黑棋棋子
                                    draw_round1(i,j,10,0x000000);
                                    draw_round2(i,j,10,0x000000);
                                    
                                    // 更新回合指示器为白棋
                                    draw_round1(600,140,30,0xF5F5F5);
                                    draw_round2(600,140,30,0xF5F5F5);
                                    
                                    // 更新棋盘数据
                                    sheet[x][y] = 1;
                                    num++;
                                    valid_move = 1;
                                    break;
                                }
                            }
                        }
                        if (valid_move) break;
                    }
                    
                    // 只有成功下子才检查胜负
                    if (valid_move) {
                        sum1=AWin(sum1);
                        //连子数为5，玩家胜利，退出循环
                        if(sum1==5)
                        {
                            draw_picture(650,120,"./picture/hei.bmp");
                            gameEnded = 1;
                            break;
                        }
                    }
                }
            }
        }
        // 电脑回合（白棋）
        else
        {
            // 延迟一会儿，让玩家看到电脑在思考
            usleep(500000); // 500ms
            
            // 电脑下子
            computerMove(&num);
            
            // 检查电脑是否获胜
            sum2=BWin(sum2);
            if(sum2==5)
            {   
                draw_picture(650,120,"./picture/bai.bmp");
                gameEnded = 1;
                break;              
            }
        }
        
        // 添加小延迟，避免过度占用CPU
        usleep(10000); // 10ms
    }

    // 游戏结束状态处理
    if (gameEnded)
    {
        while (1)
        {
            int touch_result = direction();
            if(touch_result == 0) // 只有检测到有效点击才处理
            {
                // 返回主界面：确保彻底清理
                if(end_x<800 && end_y>380 &&end_x>700 &&end_y<480)
                {
                    chess_again();
                    gameEnded = 0; // 重置结束状态
                    longjmp(jmpbuffer,1);
                }
                // 重玩：强制重置所有游戏变量
                else if(end_x<560 && end_y>380 &&end_x>480 &&end_y<480)
                {
                    // 重置游戏结束状态
                    gameEnded = 0;
                    
                    // 触发重玩处理逻辑，包括双缓冲重绘
                    chess_again(); // 清空棋盘数组
                    num = 0;       // 重置落子数
                    sum1 = 0;      // 重置连子计数
                    sum2 = 0;
                    
                    // 使用双缓冲技术重绘界面，避免闪烁
                    prepare_double_buffer();
                    
                    // 在后缓冲区绘制所有内容
                    draw_background_buffer(0xffffff);
                    draw_picture_buffer(0, 0, "./picture/checkerboard.bmp");
                    draw_picture_buffer(500, 0, "./picture/what.bmp");
                    draw_picture_buffer(700, 380, "./picture/huitui.bmp");
                    draw_picture_buffer(480, 400, "./picture/gameagain.bmp");
                    draw_picture_buffer(720, 0, "./picture/surrender.bmp");
                    
                    // 特殊处理checkerboard函数，先临时切换到缓冲区绘制
                    int *temp_lcd_fp = lcd_fp;
                    lcd_fp = back_buffer;
                    checkerboard();
                    lcd_fp = temp_lcd_fp;
                    
                    // 在后缓冲区绘制回合提示
                    draw_round_buffer(600, 140, 30, 0x000000);
                    
                    // 一次性交换缓冲区，避免闪烁
                    swap_buffer();
                    
                    goto again; // 跳回游戏开始逻辑
                }
            }
            usleep(10000);
        }
    }

    //清空数组，棋盘清理
    chess_again();
}